// -*- coding: utf-8 -*-
/*
author: zengbin93
email: zeng_bin8888@163.com
create_dt: 2022/12/16 19:37
describe: 策略分析相关功能
*/

use crate::svc::base::{DataFrame, StyleConfig};
use serde_json::Value;
use std::collections::HashMap;

/// 显示Optuna研究结果
pub fn show_optuna_study(df: &DataFrame, config: Option<&StyleConfig>) -> DataFrame {
    let config = config.unwrap_or(&StyleConfig::default());
    
    let mut result = DataFrame::new();
    result.add_column("参数", crate::svc::base::DataType::String, false);
    result.add_column("最优值", crate::svc::base::DataType::Number, true);
    result.add_column("搜索范围", crate::svc::base::DataType::String, false);
    result.add_column("重要性", crate::svc::base::DataType::Number, true);
    
    result
}

/// 显示CZSC交易员
pub fn show_czsc_trader(df: &DataFrame, config: Option<&StyleConfig>) -> DataFrame {
    let config = config.unwrap_or(&StyleConfig::default());
    
    let mut result = DataFrame::new();
    result.add_column("交易员", crate::svc::base::DataType::String, false);
    result.add_column("策略", crate::svc::base::DataType::String, false);
    result.add_column("收益", crate::svc::base::DataType::Number, true);
    result.add_column("夏普比率", crate::svc::base::DataType::Number, true);
    result.add_column("最大回撤", crate::svc::base::DataType::Number, true);
    
    result
}

/// 显示最近策略
pub fn show_strategies_recent(df: &DataFrame, config: Option<&StyleConfig>) -> DataFrame {
    let config = config.unwrap_or(&StyleConfig::default());
    
    let mut result = DataFrame::new();
    result.add_column("策略名称", crate::svc::base::DataType::String, false);
    result.add_column("创建时间", crate::svc::base::DataType::String, false);
    result.add_column("状态", crate::svc::base::DataType::String, false);
    result.add_column("收益", crate::svc::base::DataType::Number, true);
    
    result
}

/// 显示收益贡献
pub fn show_returns_contribution(df: &DataFrame, config: Option<&StyleConfig>) -> DataFrame {
    let config = config.unwrap_or(&StyleConfig::default());
    
    let mut result = DataFrame::new();
    result.add_column("策略", crate::svc::base::DataType::String, false);
    result.add_column("收益贡献", crate::svc::base::DataType::Number, true);
    result.add_column("权重", crate::svc::base::DataType::Number, true);
    result.add_column("贡献度", crate::svc::base::DataType::Number, true);
    
    result
}

/// 显示标的基准
pub fn show_symbols_bench(df: &DataFrame, config: Option<&StyleConfig>) -> DataFrame {
    let config = config.unwrap_or(&StyleConfig::default());
    
    let mut result = DataFrame::new();
    result.add_column("标的", crate::svc::base::DataType::String, false);
    result.add_column("策略收益", crate::svc::base::DataType::Number, true);
    result.add_column("基准收益", crate::svc::base::DataType::Number, true);
    result.add_column("超额收益", crate::svc::base::DataType::Number, true);
    
    result
}

/// 显示季度效应
pub fn show_quarterly_effect(df: &DataFrame, config: Option<&StyleConfig>) -> DataFrame {
    let config = config.unwrap_or(&StyleConfig::default());
    
    let mut result = DataFrame::new();
    result.add_column("季度", crate::svc::base::DataType::String, false);
    result.add_column("平均收益", crate::svc::base::DataType::Number, true);
    result.add_column("标准差", crate::svc::base::DataType::Number, true);
    result.add_column("样本数", crate::svc::base::DataType::Number, false);
    
    result
}

/// 显示CTA期间分类
pub fn show_cta_periods_classify(df: &DataFrame, config: Option<&StyleConfig>) -> DataFrame {
    let config = config.unwrap_or(&StyleConfig::default());
    
    let mut result = DataFrame::new();
    result.add_column("期间", crate::svc::base::DataType::String, false);
    result.add_column("策略收益", crate::svc::base::DataType::Number, true);
    result.add_column("基准收益", crate::svc::base::DataType::Number, true);
    result.add_column("胜率", crate::svc::base::DataType::Number, true);
    
    result
}

/// 显示波动率分类
pub fn show_volatility_classify(df: &DataFrame, config: Option<&StyleConfig>) -> DataFrame {
    let config = config.unwrap_or(&StyleConfig::default());
    
    let mut result = DataFrame::new();
    result.add_column("波动率区间", crate::svc::base::DataType::String, false);
    result.add_column("平均收益", crate::svc::base::DataType::Number, true);
    result.add_column("样本数", crate::svc::base::DataType::Number, false);
    result.add_column("胜率", crate::svc::base::DataType::Number, true);
    
    result
}

/// 显示组合分析
pub fn show_portfolio(df: &DataFrame, config: Option<&StyleConfig>) -> DataFrame {
    let config = config.unwrap_or(&StyleConfig::default());
    
    let mut result = DataFrame::new();
    result.add_column("组合", crate::svc::base::DataType::String, false);
    result.add_column("权重", crate::svc::base::DataType::Number, true);
    result.add_column("收益", crate::svc::base::DataType::Number, true);
    result.add_column("风险", crate::svc::base::DataType::Number, true);
    result.add_column("夏普比率", crate::svc::base::DataType::Number, true);
    
    result
}

/// 显示换手率
pub fn show_turnover_rate(df: &DataFrame, config: Option<&StyleConfig>) -> DataFrame {
    let config = config.unwrap_or(&StyleConfig::default());
    
    let mut result = DataFrame::new();
    result.add_column("日期", crate::svc::base::DataType::String, false);
    result.add_column("换手率", crate::svc::base::DataType::Number, true);
    result.add_column("累计换手率", crate::svc::base::DataType::Number, true);
    result.add_column("平均换手率", crate::svc::base::DataType::Number, true);
    
    result
}

/// 显示统计比较
pub fn show_stats_compare(df: &DataFrame, config: Option<&StyleConfig>) -> DataFrame {
    let config = config.unwrap_or(&StyleConfig::default());
    
    let mut result = DataFrame::new();
    result.add_column("指标", crate::svc::base::DataType::String, false);
    result.add_column("策略A", crate::svc::base::DataType::Number, true);
    result.add_column("策略B", crate::svc::base::DataType::Number, true);
    result.add_column("差异", crate::svc::base::DataType::Number, true);
    
    result
}

/// 显示标的惩罚
pub fn show_symbol_penalty(df: &DataFrame, config: Option<&StyleConfig>) -> DataFrame {
    let config = config.unwrap_or(&StyleConfig::default());
    
    let mut result = DataFrame::new();
    result.add_column("标的", crate::svc::base::DataType::String, false);
    result.add_column("惩罚系数", crate::svc::base::DataType::Number, true);
    result.add_column("原因", crate::svc::base::DataType::String, false);
    result.add_column("生效时间", crate::svc::base::DataType::String, false);
    
    result
}

/// 显示多重回测
pub fn show_multi_backtest(df: &DataFrame, config: Option<&StyleConfig>) -> DataFrame {
    let config = config.unwrap_or(&StyleConfig::default());
    
    let mut result = DataFrame::new();
    result.add_column("策略", crate::svc::base::DataType::String, false);
    result.add_column("年化收益", crate::svc::base::DataType::Number, true);
    result.add_column("年化波动率", crate::svc::base::DataType::Number, true);
    result.add_column("夏普比率", crate::svc::base::DataType::Number, true);
    result.add_column("最大回撤", crate::svc::base::DataType::Number, true);
    result.add_column("胜率", crate::svc::base::DataType::Number, true);
    
    result
}

/// 计算策略绩效指标
pub fn calculate_strategy_performance(returns: &[f64], benchmark_returns: &[f64]) -> HashMap<String, f64> {
    let mut performance = HashMap::new();
    
    if returns.is_empty() {
        return performance;
    }
    
    // 基本统计指标
    let total_return = returns.iter().fold(1.0, |acc, &ret| acc * (1.0 + ret)) - 1.0;
    let annualized_return = calculate_annualized_return(returns, 252.0);
    let volatility = calculate_volatility(returns);
    let sharpe_ratio = if volatility > 0.0 {
        annualized_return / volatility
    } else {
        0.0
    };
    let max_drawdown = calculate_max_drawdown_from_returns(returns);
    let calmar_ratio = if max_drawdown > 0.0 {
        annualized_return / max_drawdown
    } else {
        0.0
    };
    
    // 胜率
    let win_count = returns.iter().filter(|&&r| r > 0.0).count();
    let win_rate = win_count as f64 / returns.len() as f64;
    
    performance.insert("总收益".to_string(), total_return);
    performance.insert("年化收益".to_string(), annualized_return);
    performance.insert("年化波动率".to_string(), volatility);
    performance.insert("夏普比率".to_string(), sharpe_ratio);
    performance.insert("最大回撤".to_string(), max_drawdown);
    performance.insert("卡玛比率".to_string(), calmar_ratio);
    performance.insert("胜率".to_string(), win_rate);
    
    performance
}

/// 计算年化收益率
fn calculate_annualized_return(returns: &[f64], periods_per_year: f64) -> f64 {
    if returns.is_empty() {
        return 0.0;
    }
    
    let total_return = returns.iter().fold(1.0, |acc, &ret| acc * (1.0 + ret)) - 1.0;
    let num_periods = returns.len() as f64;
    
    if num_periods > 0.0 {
        (1.0 + total_return).powf(periods_per_year / num_periods) - 1.0
    } else {
        0.0
    }
}

/// 计算波动率
fn calculate_volatility(returns: &[f64]) -> f64 {
    if returns.is_empty() {
        return 0.0;
    }
    
    let mean_return = returns.iter().sum::<f64>() / returns.len() as f64;
    let variance = returns.iter()
        .map(|r| (r - mean_return).powi(2))
        .sum::<f64>() / returns.len() as f64;
    
    variance.sqrt()
}

/// 从收益率计算最大回撤
fn calculate_max_drawdown_from_returns(returns: &[f64]) -> f64 {
    if returns.is_empty() {
        return 0.0;
    }
    
    let mut cumulative = vec![1.0];
    for &ret in returns {
        let last_value = cumulative.last().unwrap();
        cumulative.push(last_value * (1.0 + ret));
    }
    
    let mut max_drawdown = 0.0;
    let mut peak = cumulative[0];
    
    for &value in &cumulative {
        if value > peak {
            peak = value;
        }
        
        let drawdown = (peak - value) / peak;
        if drawdown > max_drawdown {
            max_drawdown = drawdown;
        }
    }
    
    max_drawdown
} 